import json
import os
import random
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, List

class PCFDataLoader:
    """Data loader for PCF subscription information"""
    
    def __init__(self, data_dir: str = "data"):
        self.data_dir = data_dir
        self._cache = {}
        self._load_predefined_data()
    
    def _load_predefined_data(self):
        """Load all predefined MSISDN data from JSON files"""
        if not os.path.exists(self.data_dir):
            return
        
        for filename in os.listdir(self.data_dir):
            if filename.endswith('.json'):
                msisdn = filename.replace('.json', '')
                filepath = os.path.join(self.data_dir, filename)
                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        data = json.load(f)
                        self._cache[msisdn] = data
                except Exception as e:
                    print(f"Warning: Could not load {filepath}: {e}")
    
    def get_msisdn_data(self, msisdn: str) -> List[Dict[str, Any]]:
        """Get PCF data for a specific MSISDN"""
        # Check if we have predefined data
        if msisdn in self._cache:
            return self._cache[msisdn]
        
        # Generate demo data for unknown MSISDNs
        return self._generate_demo_data(msisdn)
    
    def _generate_demo_data(self, msisdn: str) -> List[Dict[str, Any]]:
        """Generate demo data for unknown MSISDNs in PCF format"""
        imsi = f"46000405263{random.randint(5000, 9999)}"
        
        # Generate subscriber record
        subscriber_record = {
            "regPcf": f"PCF{random.randint(1, 999):03d}UDR{random.randint(1, 999):03d}",
            "subscriberId": msisdn,
            "msisdn": msisdn,
            "status": random.choice(["Custom1", "Custom2", "Active", "Inactive"]),
            "paidType": random.choice(["NULL", "PREPAID", "POSTPAID"]),
            "grade": random.choice(["NULL", "VIP", "GOLD", "SILVER"]),
            "billingCycleDate": str(random.randint(1, 31)),
            "stateOfEmergency": random.choice(["NotEmergency", "Emergency"]),
            "gbrUl": str(random.randint(0, 1000000000)),
            "gbrDl": str(random.randint(0, 1000000000)),
            "packageType": random.choice(["NULL", "BASIC", "PREMIUM", "UNLIMITED"]),
            "imsi": imsi,
            "nextResetDateTime": (datetime.now() + timedelta(days=random.randint(1, 30))).strftime("%Y-%m-%d %H:%M:%S"),
            "usrLocationIndex": random.choice(["NULL", "1", "2", "3"]),
            "usrImeiList": random.choice(["NULL", f"862549060127{random.randint(140, 999)}"]),
            "usr5gStatus": str(random.randint(0, 1)),
            "usrExtensionStatus": "11111111",
            "usrMultiLocIndex": random.choice(["NULL", "1", "2"]),
            "rawResult": f"\r\n+++    USCDB        {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\r\nPGW    #{random.randint(100000, 999999)}\r\n%%LST PCMCCSUB: USRIDENTIFIER=\"{msisdn}\";%%\r\nRETCODE = 0 Operation succeeded\r\n\r\nSubscriber ID   MSISDN                Status        Paid Type   Grade         Billing Cycle Date    State of emergency    GBR-UL                GBR-DL                Package Type          IMSI             Next Reset Date Time  usrLocationIndex   usrIMEIList   Usr5GStatus      usrExtensionStatus   usrMultiLocIndex\r\n{msisdn}   {msisdn}         Custom1       NULL        NULL          1                     NotEmergency          0                     0                     NULL                  {imsi}  {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}   NULL               NULL          0                11111111             NULL\r\n\r\nTotal count = 1\r\n\r\nThere is together 1 report\r\n\r\n---    END"
        }
        
        # Generate service records
        service_names = [
            "22210000300000000000000000001516",
            "11000030000000000000202409200001", 
            "22210000300000000000000000001502"
        ]
        
        service_records = []
        for i, service_name in enumerate(service_names):
            service_record = {
                "regPcf": f"PCF{random.randint(1, 999):03d}UDR{random.randint(1, 999):03d}",
                "serviceName": service_name,
                "startDate": (datetime.now() - timedelta(days=random.randint(1, 30))).strftime("%Y-%m-%d %H:%M:%S") if i == 0 else None,
                "expiryDate": (datetime.now() + timedelta(days=random.randint(30, 90))).strftime("%Y-%m-%d %H:%M:%S") if i == 0 else None,
                "serviceUsageState": str(random.randint(1, 3)) if i == 0 else None,
                "serviceBillingType": random.choice(["NULL", "PREPAID", "POSTPAID"]) if i == 0 else None,
                "userLocation": random.choice(["NULL", "Shanghai", "Beijing", "Guangzhou"]) if i == 0 else None,
                "userApnOrDnn": random.choice(["NULL", "CMNET", "CMWAP", "IMS"]) if i == 0 else None,
                "serviceAuxiliaryInformation": random.choice(["NULL", "Additional Info"]) if i == 0 else None,
                "rawResult": f"\r\n+++    USCDB        {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\r\nPGW    #{random.randint(100000, 999999)}\r\n%%LST PCMCCSRV: USRIDENTIFIER=\"{msisdn}\";%%\r\nRETCODE = 0 Operation succeeded\r\n\r\nService Name                      Start Date            Expiry Date           Service Usage State   Service Billing Type  User Location   User APN or DNN   Service auxiliary information\r\n{service_name}  {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}   {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}   1                     NULL                  NULL            NULL              NULL\r\n\r\nTotal count = 1\r\n\r\nThere is together 1 report\r\n\r\n---    END" if i == 0 else None
            }
            service_records.append(service_record)
        
        # Combine all records
        all_records = [subscriber_record] + service_records
        return all_records
    
    def get_available_msisdns(self) -> list:
        """Get list of available predefined MSISDNs"""
        return list(self._cache.keys())
    
    def add_msisdn_data(self, msisdn: str, data: List[Dict[str, Any]]) -> bool:
        """Add new MSISDN data to the cache and save to file"""
        try:
            # Ensure data directory exists
            os.makedirs(self.data_dir, exist_ok=True)
            
            # Add to cache
            self._cache[msisdn] = data
            
            # Save to file
            filepath = os.path.join(self.data_dir, f"{msisdn}.json")
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(data, f, indent=4, ensure_ascii=False)
            
            return True
        except Exception as e:
            print(f"Error saving MSISDN data: {e}")
            return False 